<template>
  <a-modal v-model:visible="visible" :title="title" :width="width" unmount-on-close :mask-closable="false" @cancel="onClose" @ok="onOk">
    <div class="flex" :class="layout === 'horizontal' ? 'flex-row' : 'flex-col'">
      <template v-for="list in data">
        <template v-if="list.type === 'input'">
          <template v-for="item in list.children" :key="item">
            <div :class="{ 'last:mt-5': list.children.length > 1 }">
              {{ item.first }}
              <i-input-number
                :style="{ width: '150px' }"
                v-model="item.value"
                :unit="item.unit"
                :precision="item.precision"
                :min="0"
                :max="99999"
              >
                <template #append v-if="item.slotName">
                  <slot :name="item.slotName"></slot>
                </template>
              </i-input-number>
              {{ item.second }}
            </div>
          </template>
        </template>
        <template v-if="list.type === 'select'">
          <template v-for="item in list.children" :key="item">
            <div :class="{ 'last:mt-5': list.children.length > 1, 'mt-5': data.length > 1 && layout === 'vertical' }">
              {{ item.first }} <a-select v-model="item.value" :style="{ width: '150px' }" :options="hours" /> {{ item.second }}
            </div>
          </template>
        </template>
      </template>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
  import { computed, withDefaults, defineProps } from 'vue'
  import { hours } from '../models'

  type Props = {
    title: string
    width?: string
    modelValue: boolean
    layout: 'horizontal' | 'vertical'
    data: {
      type: 'input' | 'select'
      ident?: any
      children: {
        first?: string
        second?: string
        slotName?: any
        unit?: string
        precision?: number
        value?: number | string
      }[]
    }[]
  }

  const props = withDefaults(defineProps<Props>(), {
    modelValue: false,
    layout: 'horizontal',
    title: '设置间隔时间',
    width: '45vw',
    data: () => [
      {
        type: 'input',
        children: [],
      },
      {
        type: 'select',
        children: [],
      },
    ],
  })

  const emits = defineEmits(['update:modelValue', 'update:inputNumber', 'ok', 'close'])

  const visible = computed({
    get: () => props.modelValue,
    set: (val) => emits('update:modelValue', val),
  })

  const onClose = () => {
    emits('update:modelValue', false)
    emits('close')
  }

  const onOk = () => {
    const result: any = {
      type: '',
      value: [],
    }
    props.data.forEach((item) => {
      result.type = item.ident
      item.children.forEach((child: any) => {
        result.value.push(child.value)
      })
    })
    emits('ok', result)
  }
</script>

<style lang="less" scoped></style>
